package com.tdam2011.grupo02.appwidget;

import java.util.Date;
import java.util.LinkedList;

import com.tdam2011.grupo02.R;
import com.tdam2011.grupo02.data.DatabaseHelperSingleton;
import com.tdam2011.grupo02.domain.MensajeWeb;
import com.tdam2011.grupo02.ui.MsgwConversationListActivity;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.widget.RemoteViews;

public class ContactDroidWidgetProvider extends AppWidgetProvider {

	private static LinkedList<RemoteViews> childs;

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		childs = new LinkedList<RemoteViews>();

		final int N = appWidgetIds.length;
		for (int i = 0; i < N; i++) {
			int appWidgetId = appWidgetIds[i];
			RemoteViews views = new RemoteViews(context.getPackageName(),
					R.layout.app_widget_container);

			LinkedList<MensajeWeb> widgetContacts = DatabaseHelperSingleton
					.getInstance(context.getApplicationContext())
					.getDatabaseHelper().getAllReceivedMessage();

			RemoteViews message;
			Intent conversation;
			int count = 0;
			for (MensajeWeb widgetContact : widgetContacts) {
				message = new RemoteViews(context.getPackageName(),
						R.layout.app_widget_message);
				message.setTextViewText(R.id.txtvAppWidgetContactName,
						widgetContact.getContacto());
				Date installDate = new Date(widgetContact.getFecha());
				String timeFormat = DateFormat.getTimeFormat(context).format(
						installDate);
				String dateFormat = DateFormat.getDateFormat(context).format(
						installDate);
				message.setTextViewText(R.id.txtvAppWidgetMessageDate,
						dateFormat);
				message.setTextViewText(R.id.txtvAppWidgetMessageTime,
						timeFormat);
				message.setTextViewText(R.id.txtvAppWidgetMessage,
						widgetContact.getMensaje());
				addClickListeners(appWidgetId, message, context, count);
				
				conversation = new Intent(context, MsgwConversationListActivity.class);
				conversation.putExtra("name", widgetContact.getContacto());
				conversation.setData(Uri.parse(conversation.toUri(Intent.URI_INTENT_SCHEME)));
				PendingIntent pendingIntent = PendingIntent.getActivity(
						context, 0, conversation, PendingIntent.FLAG_UPDATE_CURRENT);
				message.setOnClickPendingIntent(R.id.layoutAppWidgetMessage, pendingIntent);
				childs.add(message);
				count++;
			}
			views.addView(R.id.vfAppWidgetContainer, childs.get(0));
			appWidgetManager.updateAppWidget(appWidgetId, views);
		}
	}

	protected void addClickListeners(int widgetId, RemoteViews root,
			Context context, int count) {
		root.setOnClickPendingIntent(
				R.id.imgvAppWidgetNext,
				getNavigationIntent(widgetId, R.id.imgvAppWidgetNext, context,
						count));
		root.setOnClickPendingIntent(
				R.id.imgvAppWidgetPrevious,
				getNavigationIntent(widgetId, R.id.imgvAppWidgetPrevious,
						context, count));
	}

	protected PendingIntent getNavigationIntent(int widgetId, final int id,
			Context context, int count) {
		Intent clickIntent = new Intent(context,
				ContactDroidWidgetProvider.class);
		clickIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
		clickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);
		clickIntent.putExtra("TRIGGER", id);
		clickIntent.putExtra("count", count);
		clickIntent.setData(Uri.parse(clickIntent
				.toUri(Intent.URI_INTENT_SCHEME)));

		PendingIntent pendingIntent = PendingIntent.getBroadcast(
				context.getApplicationContext(), 0, clickIntent,
				PendingIntent.FLAG_UPDATE_CURRENT);
		return pendingIntent;
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		Bundle extras = intent.getExtras();
		Integer id = (Integer) (extras == null ? null : extras.get("TRIGGER"));
		if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)
				&& id != null) {
			int widgetId = extras
					.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, 0);
			int count = extras.getInt("count", 0);
			onNavigate(context, widgetId, id, count);
		} else {
			super.onReceive(context, intent);
		}
	}

	protected void onNavigate(Context context, Integer widgetId, Integer id,
			int count) {
		AppWidgetManager appWidgetManager = AppWidgetManager
				.getInstance(context);
		RemoteViews root = new RemoteViews(context.getPackageName(),
				R.layout.app_widget_container);
		int child;
		if (id == R.id.imgvAppWidgetPrevious)
			child = (count == 0) ? childs.size() - 1 : count - 1;
		else
			child = (count == childs.size() - 1) ? 0 : count + 1;

		root.removeAllViews(R.id.vfAppWidgetContainer);
		root.addView(R.id.vfAppWidgetContainer, childs.get(child));

		appWidgetManager.updateAppWidget(widgetId, root);
	}
}
